<!--
 * @Description: 
 * @version: 
 * @Author: 171
 * @Date: 2022-09-01 20:22:25
 * @LastEditors: 171
 * @LastEditTime: 2022-09-22 17:54:27
-->
<script lang="ts" setup>
  import { onBeforeMount, onMounted, reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { postMyApiLogin, postMyApiRegister } from "../server"
  import router from '@/router';
  import useStore from "../stores"

  const { userState } = useStore()

  // ------------------------------------------------------------
  // 登录和注册的切换，true对应登录，false对应注册
  const service = ref<boolean>(true) 

  onBeforeMount(() => {
    const item = localStorage.getItem("login-register");
    if(item !== undefined) localStorage.setItem("login-register", "true");
    service.value = Boolean(item);
  })

  const changeService = (flag: boolean) => {
    service.value = flag;
    resetForm(ruleFormRef.value); 
  }

  // ------------------------------------------------------------
  // 处理表单数据和验证
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive({
    account: '',
    password: '',
  })

  const validateAccount = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请输入账号'))
    } else if(value.length < 6 || value.length > 15){
      callback(new Error('账号长度应在8-15位'))
    } else {
      callback();
    }
  }

  const validatePassword = (rule: any, value: any, callback: any) => {
    const re =/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/;
    if (value === '') {
      callback(new Error('请输入密码'))
    } else if(!re.test(value)){
      callback(new Error('密码至少包含数字和大写、小写字母，且长度应在8-20位'))
    } else {
      callback();
    }
  }

  const rules = reactive<FormRules>({
    account: [
      { validator: validateAccount, trigger: 'blur' }
    ],
    password: [
      // { required: true, message: 'Please input password', trigger: 'blur' },
      { validator: validatePassword, trigger: 'blur' }
    ],
  })

  const loginSuccess = (token: string, publicKey: string, id: string) => { // 登录成功后的回调
    ElMessage({
      message: '登录成功',
      type: 'success',
      duration: 1500,
      onClose: () => {      
        localStorage.setItem("token", token);
        localStorage.setItem("publicKey", publicKey);
        localStorage.setItem("id", id);
        userState.updateToken();
        userState.updateUserInfo();
        router.push('/')
      }
    })
  }

  const loginFail = () => { // 注册失败后的回调
    ElMessage({
      message: '账号密码错误，请重新输入',
      type: 'error',
      duration: 1500,
    })
  }

  const registerSuccess = () => { // 注册成功后的回调
    ElMessage({
      message: '注册成功',
      type: 'success',
      duration: 1500,
      onClose: () => {
        service.value = true;
      }
    })
  }

  const registerFail = () => { // 注册失败后的回调
    ElMessage({
      message: '注册账号重复，请输入新的账号',
      type: 'error',
      duration: 1500,
    })
  }

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) { 
        if(service.value){
          postMyApiLogin({
            account: ruleForm.account,
            password: ruleForm.password
          }, loginSuccess, loginFail);
        }else {
          postMyApiRegister({
            account: ruleForm.account,
            password: ruleForm.password
          }, registerSuccess, registerFail);
        }
      }
    })
  }

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }

</script>

<template>
   
  <div class="login">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="animate__animated animate__fadeInUp form"
      size="large"
      status-icon
    >
      <el-form-item >
        <div v-if="service" @click="changeService(false)"
          style="color: #a6a3a3" class="flex items-center ml-auto cursor-pointer"
        >     
          <span>前往注册</span>
          <el-icon :size="17"><Right /></el-icon>
        </div>
        <div v-else @click="changeService(true)"
          style="color: #a6a3a3" class="flex items-center ml-auto cursor-pointer"
        >
          <el-icon :size="17"><Back /></el-icon>
          <span>返回登录</span>
        </div>
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input v-model="ruleForm.account" :input-style="{color: '#fff'}" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" :input-style="{color: '#fff'}"/>
      </el-form-item>
    
      <el-form-item class="btn">
        
          <el-button size="large" round type="success" @click="submitForm(ruleFormRef)">
            <transition enter-active-class="animate__animated animate__jackInTheBox">
              <span v-if="service">登录</span> 
              <span v-else>注册</span>
            </transition>
          </el-button>
        
        <el-button round type="primary" @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  
  
</template>



<style scoped lang="less">
.login{
  width: 40%;
  height: 40%;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
  .form{
    width: 60%;
    border-radius: 5px;
    :deep(.el-input__wrapper){
      background-color: transparent;
      border-color: #fff;     
    }
    :deep(.el-form-item__label){
      color: #fff;
      font-weight: bold;
      font-size: 16px;
    }
    .btn{
      width: 100%;
      :deep(.el-form-item__content){
        @apply flex justify-around;
        margin-left: 32px;
      }
      :deep(.el-button){
        width: 35%;
      }
    }
  }
}
</style>